package cn.toma.core.exception;

import cn.toma.common.exception.FfBootException;
import cn.toma.common.vo.StringPool;
import cn.toma.core.result.ResponseResult;
import cn.toma.core.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Set;

/**
 * @author zqx
 * @version 1.0.0
 * @ClassName GlobalExceptionHandler.java
 * @Description 全局异常处理器
 * @createTime 2019年08月28日 14:25:00
 */

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseResult
{


	/**
	 * 处理未被定义的异常
	 *
	 * @param e
	 * @param request
	 * @return
	 */
	@ExceptionHandler(value = Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public Result handleException(Exception e, HttpServletRequest request)
	{
		String format = String.format("接口 [%s] 出现异常，请求方法：%s，异常摘要：%s", request.getRequestURI(), request.getMethod(), e.getMessage());
		log.error("Exception : {}", format);
		return getFailedObj(HttpStatus.INTERNAL_SERVER_ERROR.value(), "接口 [" + request.getRequestURI() + "] 内部错误");
	}

	/**
	 * 处理自定义全局异常
	 *
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = GlobalException.class)
	public Result handleException(GlobalException e)
	{
		log.error("GlobalException {}：{}", e.getCodeMsg().getCode(), e.getCodeMsg().getMsg());
		return getFailedObj(e.getCodeMsg());
	}

	/**
	 * 处理自定义全局异常
	 *
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = FfBootException.class)
	public Result handleException(FfBootException e)
	{
		log.error("系统错误：{}", e.getMessage());
		return getFailedObj(e.getMessage());
	}




	/**
	 * 处理 NoHandlerFoundException 404 异常
	 *
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = NoHandlerFoundException.class)
	@ResponseStatus(HttpStatus.NOT_FOUND)
	public Result handleException(NoHandlerFoundException e)
	{
		log.error("NoHandlerFoundException  {}：{}", HttpStatus.NOT_FOUND.value(), "接口 [" + e.getRequestURL() + "] 不存在");
		return getFailedObj(HttpStatus.NOT_FOUND.value(), "接口 [" + e.getRequestURL() + "] 不存在");
	}


	/**
	 * 统一处理请求参数校验(实体对象传参)
	 *
	 * @param e BindException
	 * @return Result
	 */
	@ExceptionHandler(BindException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public Result validExceptionHandler(BindException e)
	{
		StringBuilder message = new StringBuilder();
		List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
		for (FieldError error : fieldErrors) {
			message.append(error.getField()).append(error.getDefaultMessage()).append(StringPool.COMMA);
		}
		message = new StringBuilder(message.substring(0, message.length() - 1));
		return getFailedObj(message.toString());

	}

	/**
	 * 统一处理请求参数校验(普通传参)
	 *
	 * @param e ConstraintViolationException
	 * @return FebsResponse
	 */
	@ExceptionHandler(value = ConstraintViolationException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public Result handleConstraintViolationException(ConstraintViolationException e)
	{
		StringBuilder message = new StringBuilder();
		Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
		for (ConstraintViolation<?> violation : violations) {
			Path path = violation.getPropertyPath();
			String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), StringPool.DOT);
			message.append(pathArr[1]).append(violation.getMessage()).append(StringPool.COMMA);
		}
		message = new StringBuilder(message.substring(0, message.length() - 1));
		return getFailedObj(HttpStatus.BAD_REQUEST.value(),message.toString());
	}




}
